# -*- coding: utf-8 -*-
from pyquery import PyQuery
from datetime import datetime
from norincogroup.items import NorSku
from zc_core.model.items import Catalog, ItemData, ItemDataSupply
from norincogroup.matcher import *
from norincogroup.dao.catalog_dao import norincogroup_catalogDao
import json
from zc_core.pipelines.helper.catalog_helper import CatalogHelper


# 解析catalog列表
def parse_catalog(response):
    response_text = response.text
    response_json = json.loads(response_text[response_text.index('(') + 1:response_text.rindex(')')])
    cats = list()
    for index_1, i in enumerate(response_json):
        # 默认 工业类,消费类,福利超市,酒店专区
        for p in ['工业类', '消费类', '']:
            if i['flag01str'] == p:
                pzname_1 = i['pzname']
                pzid_1 = i['pzid']
                father_1 = i['father']
                ecWzpz_1 = i['ecWzpz']
                value_1 = i['value']
                cat1 = _build_catalog(pzid_1, pzname_1, father_1, 1)
                cats.append(cat1)
                for index_2, j in enumerate(ecWzpz_1):
                    pzname_2 = j['pzname']
                    pzid_2 = j['pzid']
                    father_2 = j['father']
                    ecWzpz_2 = j['ecWzpz']
                    value_2 = j['value']
                    cat2 = _build_catalog(pzid_2, pzname_2, father_2, 2)
                    cats.append(cat2)
                    for index_3, k in enumerate(ecWzpz_2):
                        pzname_3 = k['pzname']
                        pzid_3 = k['pzid']
                        father_3 = k['father']
                        ecWzpz_3 = k['ecWzpz']
                        value_3 = k['value']
                        cat3 = _build_catalog(pzid_3, pzname_3, father_3, 3)
                        cats.append(cat3)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 解析sku列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    total_list = [i for i in jpy(".a_togPage").items()]
    if total_list.__len__() == 0:
        return 1
    else:
        return int(total_list[-1].attr('num'))


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    jpy = PyQuery(response.text)
    gpls_list = [i.attr('gpls') for i in jpy('.fl.pro_list li').items()]
    name_list = [i.text() for i in jpy('.fl.pro_list li p > a').items()]
    catalog2Name = meta.get('catalog2Name')
    catalog2Id = meta.get('catalog2Id')
    skus = []
    for index, gpls in enumerate(gpls_list):
        sku = NorSku()
        sku['skuId'] = gpls
        sku['batchNo'] = batch_no
        sku['skuName'] = name_list[index]
        sku['catalog2Id'] = catalog2Id
        CatalogHelper().fill(sku)
        skus.append(sku)
    # print(len(skus),skus)
    return skus


# 解析app端商品详情数据
def parse_item_app_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    data = json.loads(response.text)
    result = ItemData()
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    sold_count = int(data.get('data', {}).get('sl15', 0))
    if sold_count < 0:
        sold_count = 0
    result['soldCount'] = sold_count
    # result['stock'] = data.get('data', {}).get('sl2', 0)
    result['skuName'] = data.get('data', {}).get('title')
    result['unit'] = data.get('data', {}).get('sldw2')
    result['brandName'] = data.get('data', {})['cd']
    catalog_helper = CatalogHelper()
    if data.get('data', {})['dlcode'].split(',').__len__() < 3:
        catalog2Id = data.get('data', {}).get('dlcode').split(',')[1]
        result['catalog2Id'] = catalog2Id
        catalog_helper.fill(result)
    else:
        catalog3Id = data.get('data', {}).get('dlcode').split(',')[2]
        result['catalog3Id'] = catalog3Id
        catalog_helper.fill(result)

    result['skuImg'] = data.get('data', {}).get('logoimg00')
    origin_price = float(data.get('data', {}).get('price00Str'))
    result['originPrice'] = origin_price
    result['salePrice'] = origin_price
    supplierSkuId = data.get('data', {}).get('skuidwestern')
    result['supplierSkuId'] = supplierSkuId
    result['supplierSkuCode'] = supplierSkuId
    brandModel = data.get('data', {}).get('cz', '')
    if brandModel.strip():
        result['brandModel'] = brandModel
    result['supplierName'] = data.get('data', {}).get('mbname', '')
    result['supplierId'] = str(data.get('data', {}).get('hydm', ''))
    return result


# 解析web端商品详情数据
def parse_item_data(response):
    response_text = response.text.replace('<!--', '').replace('-->', '')
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    jpy = PyQuery(response_text)
    result = ItemData()
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    salePrice = re.sub('（(.*?)）', '', jpy('.para_p.price_div').text().replace('￥', '').replace(' ', ''))
    originPrice = salePrice
    pool_list = norincogroup_catalogDao().get_cat_list_from_pool()
    catalog_list = re.findall('''onclick="searchSource3\('(.*?)\'''', response_text)[-1].split(',')

    if catalog_list.__len__() == 2:
        # 一级分页id
        catalog1Id = catalog_list[0]
        result['catalog1Id'] = catalog1Id
        # 一级分页名称
        catalog1Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog1Id][0]
        result['catalog1Name'] = catalog1Name
        # 二级分页id
        catalog2Id = catalog_list[1]
        result['catalog2Id'] = catalog2Id
        # 二级分页名称
        catalog2Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog2Id][0]
        result['catalog2Name'] = catalog2Name
    elif catalog_list.__len__() == 1:
        print('异常报错', sku_id)
    else:
        # 一级分页id
        catalog1Id = catalog_list[0]
        result['catalog1Id'] = catalog1Id
        # 一级分页名称
        catalog1Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog1Id][0]
        result['catalog1Name'] = catalog1Name
        # 二级分页id
        catalog2Id = catalog_list[1]
        result['catalog2Id'] = catalog2Id
        # 二级分页名称
        catalog2Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog2Id][0]
        result['catalog2Name'] = catalog2Name
        # 三级分页id
        catalog3Id = catalog_list[2]
        result['catalog3Id'] = catalog3Id
        # 三级分页名称
        catalog3Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog3Id][0]
        result['catalog3Name'] = catalog3Name

    if salePrice != '0.00' and salePrice != "":
        result['salePrice'] = float(salePrice.replace(',', ''))
        result['originPrice'] = float(originPrice.replace(',', ''))
        skuName = jpy('.title_h').text()
        result['skuName'] = skuName
        soldCount = re.search('\d+',
                              [i('.para_p').text() for i in jpy('.para_div').items() if i('b').text() == "历史成交："][
                                  0]).group(
        )
        result['soldCount'] = soldCount
        stock_unit_list = jpy('.para_pp').text().split()
        if stock_unit_list.__len__() == 2:
            unit = stock_unit_list[0]
            result['unit'] = unit
            stock = re.search('\d+', stock_unit_list[1].replace(',', '')).group()
            result['stock'] = stock
        else:
            unit = stock_unit_list[0]
            result['unit'] = unit
        model_list = [i('.pro_suggestpn').text() for i in jpy('.fl.pro_suggestp').items() if
                      i('.pro_suggestpa').text() == '规格：1']
        if model_list.__len__() != 0:
            brandModel = model_list[0].replace('型号：', '')
            result['brandModel'] = brandModel
        supplierName = jpy('.pro_contact a').attr('title')
        result['supplierName'] = supplierName
        supplierId = re.search('hydm = "(.*?)";', response_text).group(1)
        result['supplierId'] = supplierId
        supplierSkuCode_list = [i.text() for i in jpy('.para_div').items() if i('b').text() == 'S   K   U：']
        if supplierSkuCode_list.__len__() != 0:
            supplierSkuCode = supplierSkuCode_list[0].replace('S\xa0\xa0\xa0K\xa0\xa0\xa0U：\n', '')
            result['supplierSkuCode'] = supplierSkuCode
            result['supplierSkuId'] = supplierSkuCode
        onSaleTime_list = [i.text().replace('上架时间：\n', '') for i in jpy('.para_div').items() if
                           i('b').text() == "上架时间："]
        if onSaleTime_list.__len__() != 0:
            onSaleTime = onSaleTime_list[0]
            result['onSaleTime'] = onSaleTime
        deliveryDay = [i.text().replace('个工作日', '') for i in jpy('.para_div').items() if i('b').text() == "预计出货："]
        if deliveryDay.__len__() != 0:
            result['deliveryDay'] = deliveryDay[0].replace('预计出货：\n', '')
        skuImg = [i for i in jpy('.img_a img').items()][0]('img').attr('src')
        result['skuImg'] = skuImg
        brandName = jpy('.fl.pro_suggestpc').attr('title')
        if brandName.__len__() != 0:
            result['brandName'] = brandName
        return result
    else:
        return {"skuId": sku_id}


def supply_item_app_supplier_id(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    data = json.loads(response.text)
    result = ItemDataSupply()
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['supplierId'] = str(data['data']['hydm'])

    return result
